package com.grm.service;

import com.grm.job.SampleJob;
import org.quartz.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class QuartzService {

    private final Scheduler scheduler;

    public QuartzService(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public void startJobAtSpecificTime(Date startTime) throws SchedulerException {
        JobDetail jobDetail = buildJobDetail(SampleJob.class);
        Trigger trigger = TriggerBuilder.newTrigger().startAt(startTime).build();
        scheduler.scheduleJob(jobDetail, trigger);
    }

    public void startJobEveryFewDays(Date startTime, int intervalInDays) throws SchedulerException {
        JobDetail jobDetail = buildJobDetail(SampleJob.class);

        // withIntervalInHours 设置任务的间隔时间
        SimpleScheduleBuilder simpleScheduleBuilder =
            SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(intervalInDays * 24).repeatForever();

        Trigger trigger = TriggerBuilder.newTrigger().startAt(startTime).withSchedule(simpleScheduleBuilder).build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 每周的某个周几的某个时间点执行
     *
     * @param startTime 开始时间
     * @param dayOfWeek 星期几
     */
    public void startJobEveryFewWeeks(Date startTime, int dayOfWeek) throws SchedulerException {

        JobDetail jobDetail = buildJobDetail(SampleJob.class);
        // 指定在每周的特定日期、小时和分钟触发任务
        CronScheduleBuilder cronScheduleBuilder =
            CronScheduleBuilder.weeklyOnDayAndHourAndMinute(dayOfWeek, startTime.getHours(), startTime.getMinutes());

        Trigger trigger = TriggerBuilder.newTrigger().startAt(startTime).withSchedule(cronScheduleBuilder).build();

        scheduler.scheduleJob(jobDetail, trigger);

    }

    /**
     * 每隔几周执行
     *
     * @param startTime       开始时间
     * @param intervalInWeeks 间隔几周
     * @param dayOfWeek       星期几
     */
    public void startJobEveryFewWeeksOnSpecificWeekday(Date startTime, int intervalInWeeks, int dayOfWeek)
        throws SchedulerException {
        JobDetail jobDetail = buildJobDetail(SampleJob.class);

        // 构建Cron表达式，指定在每隔几周的星期几的特定时间点触发任务
        String cronExpression =
            String.format("%d %d %d ? * %d/%d", startTime.getSeconds(), startTime.getMinutes(), startTime.getHours(),
                dayOfWeek, intervalInWeeks);

        Trigger trigger = TriggerBuilder.newTrigger().startAt(startTime)
            .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    public void stopJob(JobKey jobKey) throws SchedulerException {
        scheduler.deleteJob(jobKey);
    }

    private JobDetail buildJobDetail(Class<? extends Job> jobClass) {
        return JobBuilder.newJob(jobClass).withIdentity(UUID.randomUUID().toString(), "sample-group").build();
    }
}
